const sharp = require('sharp');
const fs = require('fs');
const textToSvg = require('text-to-svg');

const basePicture = `aosidingzhiwuyuan01.jpg`;

/**
 * 5、添加水印
 * @param  {String} basePicture 原图路径
 * @param  {String} watermarkPicture 水印图片路径
 * @param  {String} newFilePath 输出图片路径
 */
async function addWatermark(basePicture, watermarkPicture, newFilePath) {
    let result = await sharp(basePicture)
        .composite([
            {
                input: watermarkPicture,
                top: 10,
                left: 10
            }
        ])
        .resize(800)
        .jpeg({
            quality: 100,
        })
        .toFile(newFilePath)

    console.log(result);
}

// addWatermark(
//     basePicture,
//     `${__dirname}/logo.png`,
//     `${__dirname}/1.jpg`
// );


/**
 * 添加文字，类似添加水印
 * @param {String} basePicture 原图路径
 * @param {Object} font 字体设置
 * @param {String} newFilePath 输出图片路径
 * @param {String} text 待粘贴文字
 * @param {Number} font.fontSize 文字大小
 * @param {String} font.color 文字颜色
 * @param {Number} font.left 文字距图片左边缘距离
 * @param {Number} font.top 文字距图片上边缘距离
 */
async function addText(basePicture, font, newFilePath) {
    const { fontSize, text, color, left, top } = font;
    // 同步加载文字转SVG的库
    const textToSvgSync = textToSvg.loadSync(`${__dirname}/AlibabaPuHuiTi-2-45-Light.otf`);
    // 设置文字属性
    const attributes = {
        fill: color
    };
    const options = {
        fontSize,
        anchor: 'top',
        attributes
    };
    // 文字转svg，svg转buffer
    const svgTextBuffer = Buffer.from(textToSvgSync.getSVG(text, options));

    // 添加文字
    let result = await sharp(basePicture)
        .composite([
            {
                input: svgTextBuffer,
                top,
                left
            }
        ])
        .resize(800)
        .withMetadata()
        .webp({
            quality: 100,
        })
        .toFile(newFilePath)
    console.log(result)
}

// addText(
//     basePicture,
//     {
//         fontSize: 100,
//         text: '支付宝',
//         color: 'green',
//         left: 300,
//         top: 300
//     },
//     `${__dirname}/2.jpg`
// );


async function toBase64(basePicture) {
    let result = 'data:image/jpeg;base64,' + (await sharp(basePicture)
        .resize(100)
        .toBuffer()
    ).toString('base64')

    console.log(result);
}

toBase64(basePicture);

console.log('success');